package com.dy.yunying.biz.controller.datacenter;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.dy.yunying.api.datacenter.dto.RegRetentionDto;
import com.dy.yunying.api.datacenter.vo.RegRetentionVO;
import com.dy.yunying.biz.service.datacenter.RegRetentionService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.MapUtils;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

/**
 * dogame注册留存率
 * @author hma
 * @date 2022/8/19 10:29
 */
@Slf4j
@RestController("regRetention")
@RequestMapping("/dataCenter/regRetention")
@RequiredArgsConstructor
public class RegRetentionController {

	private final RegRetentionService regRetentionService;


	/**
	 * 注册留存率分析报表
	 *
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/count")
	public R countDataTotal(@Valid @RequestBody RegRetentionDto req) {
		req.setCurrent(null);
		req.setSize(null);
		return regRetentionService.count(req);
	}


	/**
	 * 注册留存率数据列表
	 *
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/list")
	public R<List<RegRetentionVO>> list(@Valid @RequestBody RegRetentionDto req) {
		R<List<RegRetentionVO>> page = regRetentionService.page(req);
		if (CommonConstants.FAIL.equals(page.getCode())){
			return page;
		}
		List<RegRetentionVO> data = page.getData();
		deal(data);
		page.setData(data);
		return page;
	}

	private void deal(List<RegRetentionVO> data) {
		if (!CollectionUtils.isEmpty(data)){
			for (RegRetentionVO dailyDataVO : data) {
				dailyDataVO.setRetentionRate(dailyDataVO.getRetentionRate()+"%");
				dailyDataVO.setRetentionRate3(dailyDataVO.getRetentionRate3()+"%");
				dailyDataVO.setRetentionRate4(dailyDataVO.getRetentionRate4()+"%");
				dailyDataVO.setRetentionRate5(dailyDataVO.getRetentionRate5()+"%");
				dailyDataVO.setRetentionRate6(dailyDataVO.getRetentionRate6()+"%");
				dailyDataVO.setRetentionRate7(dailyDataVO.getRetentionRate7()+"%");
				dailyDataVO.setRetentionRate8(dailyDataVO.getRetentionRate8()+"%");
				dailyDataVO.setRetentionRate9(dailyDataVO.getRetentionRate9()+"%");
				dailyDataVO.setRetentionRate10(dailyDataVO.getRetentionRate10()+"%");
				dailyDataVO.setRetentionRate11(dailyDataVO.getRetentionRate11()+"%");
				dailyDataVO.setRetentionRate12(dailyDataVO.getRetentionRate12()+"%");
				dailyDataVO.setRetentionRate13(dailyDataVO.getRetentionRate13()+"%");
				dailyDataVO.setRetentionRate14(dailyDataVO.getRetentionRate14()+"%");
				dailyDataVO.setRetentionRate30(dailyDataVO.getRetentionRate30()+"%");
				dailyDataVO.setRetentionRate60(dailyDataVO.getRetentionRate60()+"%");
				dailyDataVO.setRetentionRate90(dailyDataVO.getRetentionRate90()+"%");
				dailyDataVO.setRetentionRate120(dailyDataVO.getRetentionRate120()+"%");
				dailyDataVO.setRetentionRate150(dailyDataVO.getRetentionRate150()+"%");
				dailyDataVO.setRetentionRate180(dailyDataVO.getRetentionRate180()+"%");
				dailyDataVO.setRetentionRate360(dailyDataVO.getRetentionRate360()+"%");

			}
		}

	}


	/**
	 * 注册留存率数据汇总
	 *
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/collect")
	public R collect(@Valid @RequestBody RegRetentionDto req) {
		req.setCurrent(null);
		req.setSize(null);
		R<List<RegRetentionVO>> collect = regRetentionService.collect(req);
		if (CommonConstants.FAIL.equals(collect.getCode())){
			return collect;
		}
		deal(collect.getData());
		return collect;
	}


	/**
	 * 注册留存率数据导出
	 *
	 * @param req
	 * @return
	 */
	@ResponseExcel(name = "注册留存率报表导出", sheet = "注册留存率报表导出")
	@RequestMapping("/excelExport")
	public R export(@Valid @RequestBody RegRetentionDto req, HttpServletResponse response, HttpServletRequest request) {
		req.setCurrent(null);
		req.setSize(null);
		//导出默认按照倒叙排列
		req.setKpiValue(null);
		List<RegRetentionVO> result = new ArrayList<>();
		String sheetName = "注册留存率";

		try {
			CompletableFuture<List<RegRetentionVO>> pageFuture = CompletableFuture.supplyAsync(new Supplier<List<RegRetentionVO>>() {
				@Override
				public List<RegRetentionVO> get() {
					R page = regRetentionService.page(req);
					if (CommonConstants.SUCCESS.equals(page.getCode())) {
						return (List<RegRetentionVO>) page.getData();
					}
					return null;
				}
			});

			CompletableFuture<List<RegRetentionVO>> totalFuture = CompletableFuture.supplyAsync(new Supplier<List<RegRetentionVO>>() {
				@Override
				public List<RegRetentionVO> get() {
					R page = regRetentionService.collect(req);
					if (CommonConstants.SUCCESS.equals(page.getCode())) {
						return (List<RegRetentionVO>) page.getData();
					}
					return null;
				}
			});
			List<RegRetentionVO> list = pageFuture.get();
			List<RegRetentionVO> totalList = totalFuture.get();
			if (!CollectionUtils.isEmpty(list)){
				result.addAll(list);
			}
			if (!CollectionUtils.isEmpty(totalList)){
				result.addAll(totalList);
			}
			if(!CollectionUtils.isEmpty(result)){
               deal(result);
			}
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("utf-8");
			String fileName = URLEncoder.encode("注册留存率报表-" + DateUtils.getCurrentTimeNoUnderline(), "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			response.setHeader("file-name", fileName);
			ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
			WriteSheet writeSheet0 = EasyExcel.writerSheet(0, sheetName).head(RegRetentionVO.class).build();
			excelWriter.write(result, writeSheet0);
			excelWriter.finish();
		} catch (Exception e) {
			log.error("注册留存率导出异常, 异常原因：{}",e.toString());
			throw new BusinessException("导出异常");
		}

		return null;
	}


}
